package cn.zxl.spring.holiday.job.service.impl;

import cn.zxl.spring.holiday.job.domain.Employee;
import cn.zxl.spring.holiday.job.domain.OperateLog;
import cn.zxl.spring.holiday.job.mapper.EmployeeMapper;
import cn.zxl.spring.holiday.job.mapper.OperateLogMapper;
import cn.zxl.spring.holiday.job.qo.QueryObject;
import cn.zxl.spring.holiday.job.service.OperateLogService;
import cn.zxl.spring.holiday.job.util.SessionUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bofeifei
 * @since 2021-10-01
 */
@Service
public class OperateLogServiceImpl extends ServiceImpl<OperateLogMapper, OperateLog> implements OperateLogService {

    @Autowired
    private OperateLogMapper logMapper;
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public OperateLog getLog() {
        OperateLog operateLog = new OperateLog();
        HttpServletRequest request = SessionUtil.getRequest();
        HttpSession session = SessionUtil.getSession();
        Employee user = (Employee) session.getAttribute("SESSION_USER");
        if (user != null) {
            // 获取操作人
            operateLog.setOperatorName(user.getUsername());
            Employee empDept = employeeMapper.findOneDeptById(user.getId());
            // 获取部门
            operateLog.setDeptName(empDept.getDept().getName());
        }
        // 获取请求方式
        String method = request.getMethod();
        operateLog.setRequestMethod(method);
        // 获取请求地址
        String requestURI = request.getRequestURI();
        operateLog.setOperUrl(requestURI);
        // 获取请求参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        String parameter = JSON.toJSONString(parameterMap);
        operateLog.setOperParam(parameter);
        //获取操作 ip
        String remoteAddr = request.getRemoteAddr();
        operateLog.setOperIp(remoteAddr);

        return operateLog;
    }

    @Override
    public boolean saveTote(OperateLog log) {
        return logMapper.saveTote(log);
    }

    @Override
    public PageInfo<OperateLog> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<OperateLog> operateLogs = logMapper.selectByQo(qo);
        return new PageInfo<>(operateLogs);
    }
}
